package cn.gogoyc.org.service.impl;

import cn.gogoyc.org.basic.servie.impl.BaseServiceImpl;
import cn.gogoyc.org.domain.Department;
import cn.gogoyc.org.mapper.DepartmentMapper;
import cn.gogoyc.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The type Department service.
 * 部门类Service层
 * @author Yang
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {
    @Autowired
    private DepartmentMapper mapper;

    @Override
    public List<Department> deptTree() {
        //查询所有
        List<Department> departments = mapper.loadAll();
        //1.将所有部门信息保存在map中，方便根据id去获取部门信息，就不用查数据库了
        Map<Long,Department> map = new HashMap<>();
        //遍历所有部门的集合
        for (Department department : departments) {
            //将每个部门的id和对象添加进map集合
            map.put(department.getId(),department);
        }

        //空集合
        List<Department> deptTree = new ArrayList<>();
        //再次遍历部门对象集合
        for (Department department : departments) {
            //parentid为null的肯定就是顶级部门
            if(department.getParent_id()==null){
                //将顶级部门添加进集合
                deptTree.add(department);
            }else{
                //有parentid那就是下级,获取他的上级部门id
                Long parent_id = department.getParent_id();
                //去map中根据部门id查询上级部门对象
                Department parentDepartment = map.get(parent_id);

                if (parentDepartment!=null){
                //去获取上级部门的部门树,再将子部门添加进对应的父部门的集合中
                parentDepartment.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }

}
